//
//  TSSplashViewController.m
//  UVideo-V5-iPhone
//
//  Created by CreeveLiu on 15/6/8.
//  Copyright (c) 2015年 sumavision. All rights reserved.
//

#import "TSSplashViewController.h"
#import "TSSystemUtil.h"
#import "TSSelectViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "TSBootAdUtil.h"
#import "TSPageControl.h"
#import "TSTimeUtil.h"
#import "TSXMPPMessageHandler.h"
#import "TSAccountUtil.h"

#if ShowEventTabbarItem
#import <TVPlayerSDK/TVPlayerSDK.h>
#endif

#if defined(ENABLE_AD_MODULE) || defined(Tap_Ad_Play_Guangdong)
#import "TSPlayAdViewController.h"
#endif

#import <objc/runtime.h>
#import "TSLogin4FuZhouViewController.h"

#import "TSGpsLocationUtil.h"


#ifdef ENABLE_STATISTICS

#import "TSStatisticsUtil.h"

#endif


@interface TSSplashViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *loadingImageView;
@property (weak, nonatomic) IBOutlet UIButton *skipBtn;

@end

@implementation TSSplashViewController
{
    UIScrollView        *_introScrollView;
    CGFloat             _currentMaxX;
    
    NSMutableArray    *_arrGuideImages;
    NSMutableArray   *_arrGuideImageView;
    NSArray             *_arrLocations;
    
    NSInteger           _prevScrollIndex;
    UIButton            *_rudderButton;
    UILabel             *_alertLabel;
    UIView              *_transparentView;
    
    UIImageView         *adImgView;
    UILabel             *adCountDownLabel;
    NSInteger           bootAdCountDown;

    TSBootAdInfo        *bootAdInfo;
    TSPageControl       *pageControl;
    
#if defined(ENABLE_AD_MODULE) || defined(Tap_Ad_Play_Guangdong)
    TSPlayAdViewController *_adViewController;
#endif
    
    BOOL                _isFirstLaunch;
    NSTimer             *_timerXmppLogin;
    
    UIStatusBarStyle    _prevStatusBarStyle;
    
#ifdef SWITCH_LOCATION_TRCBANK
    UIImageView *_homeUpImageView;
    UIImageView *_homeLeftImageView;
    UIImageView *_homeRightImageView;
    UIImageView *_homeDownImageView;
    
    BOOL _animated;
#endif
    
    BOOL _isLoginSuccess;
    BOOL _isNeedShowLogin;
    BOOL _isShouldDismiss;
    BOOL _isLoginComeBack;
    
#ifdef Get_Launch_Ad_Guangdong
    dispatch_semaphore_t _signal;
#endif
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isFirstLaunch = [TSCommonUtil isCurrentVersionAppFirstLaunch];
#ifdef EMBED_DEMO
    _isFirstLaunch = NO;
#endif
    
    [self layoutUI];
    [self.loadingImageView setHidden:NO];
    [self refreshBootImage];
#ifdef Loginsuccess_IntoApp
    _isNeedShowLogin = YES;
    [self loginIntoApp];
#else
    [self autoLogin];
#endif
    
    [[TSGpsLocationUtil sharedSingleton] setDelegateGpsLocation:(id<TSGpsLocationDelegate>)self];
    [[TSGpsLocationUtil sharedSingleton] startGpsLocation];
}

- (void)layoutUI
{
    
#if LauchImgAdapter
    if (self.view.frame.size.height <= 480) {
        // iPhone 4, 4s
        [self.loadingImageView setImage:[UIImage TSimageNamed:@"640x960"]];
    } else if (self.view.frame.size.height <= 568 && self.view.frame.size.height > 480) {
        // iPhone 5, 5s
        [self.loadingImageView setImage:[UIImage TSimageNamed:@"640x1136"]];
    } else if (self.view.frame.size.height <= 677 && self.view.frame.size.height > 568) {
        // iPHone 6, 6s
        [self.loadingImageView setImage:[UIImage TSimageNamed:@"750x1334"]];
    } else if (self.view.frame.size.height <= 736 && self.view.frame.size.height > 677) {
        // iPhone 6+, 6s+
        [self.loadingImageView setImage:[UIImage TSimageNamed:@"1242x2208"]];
    }
    
    self.skipBtn.layer.cornerRadius = 15.f;
    self.skipBtn.layer.borderColor = [[UIColor generalLightSeperatorColor] CGColor];
    self.skipBtn.layer.borderWidth = [UIDefine seperatorLineHeight];
    [self.skipBtn setBackgroundColor:[UIColor generalBackgroundColor]];
    [self.skipBtn setTitleColor:[UIColor generalLightTextColor] forState:UIControlStateNormal];
    [self.skipBtn addTarget:self action:@selector(onHitBtnSkip:) forControlEvents:UIControlEventTouchUpInside];
    [self.skipBtn setHidden:YES];
#else
    [self.loadingImageView setImage:[UIImage TSimageNamed:@"loading_image"]];
#endif
    
#ifdef EMBED_DEMO
    self.loadingImageView.image = [UIImage imageNamed:@"cmb_home_page"];
    self.loadingImageView.userInteractionEnabled = YES;
    [self.loadingImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onHitLoadingImage:)]];
    
#ifdef SWITCH_LOCATION_TRCBANK
    _homeUpImageView =  [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_1"]];
    _homeLeftImageView =  [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_2"]];
    _homeRightImageView =  [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_3"]];
    _homeDownImageView =  [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_4"]];
    
    [self.view addSubview:_homeUpImageView];
    [self.view addSubview:_homeLeftImageView];
    [self.view addSubview:_homeRightImageView];
    [self.view addSubview:_homeDownImageView];
    
    [self.loadingImageView setImage:nil];
    _animated = NO;
#endif
    
#endif
    
    NSInteger guideImageNumber = 5;
    
    _arrGuideImages = [NSMutableArray arrayWithCapacity:0];
    _arrGuideImageView = [NSMutableArray arrayWithCapacity:0];
    
    NSInteger startIndex = 1;
#if NewerGuideStep4
    startIndex = 2;
#endif
    
#ifdef SWITCH_LOCATION_SICHUAN_BASE415
    startIndex= 1;
    guideImageNumber = 4;
#endif
    
    for (NSInteger i = startIndex; i <= guideImageNumber; i++) {
        
        UIImage *image = [UIImage TSimageNamed:[NSString stringWithFormat:@"common_guide_%li", (long)i]];
        if (image != nil) {
            [_arrGuideImages addObject:image];
        }
    }
    
    _introScrollView = [[UIScrollView alloc] init];
    [_introScrollView setPagingEnabled:YES];
    [_introScrollView setShowsHorizontalScrollIndicator:NO];
    [_introScrollView setDelegate:(id<UIScrollViewDelegate>)self];
    [_introScrollView setHidden:YES];
    [self.view addSubview:_introScrollView];

#if NewerGuideStepHintByPageControl
    CGFloat pageControlWidth = 150;
    pageControl = [[TSPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - pageControlWidth/2, self.view.frame.size.height - 50, pageControlWidth, 20)];
#if NewerGuideStep4
    [pageControl setNumberOfPages:4];
#else
    [pageControl setNumberOfPages:guideImageNumber];
#endif
    [pageControl setCurrentPage:0];
//  [pageControl addTarget:self action:@selector(pageControlDidStopAtIndex:) forControlEvents:UIControlEventValueChanged];
    [pageControl setHidden:YES];
    [self.view addSubview:pageControl];
#endif
    
    for (UIImage *image in _arrGuideImages) {
        NSInteger index = [_arrGuideImages indexOfObject:image];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [_arrGuideImageView addObject:imageView];
        [_introScrollView addSubview:imageView];
        
        if (index == _arrGuideImages.count -1 ) {
            _rudderButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [_rudderButton setImage:[UIImage TSimageNamed:@"common_guide_btn"] forState:UIControlStateNormal];
            [_rudderButton addTarget:self action:@selector(onHitRudderButton) forControlEvents:UIControlEventTouchUpInside];
            [imageView addSubview:_rudderButton];
            [imageView setUserInteractionEnabled:YES];
            
            _alertLabel = [[UILabel alloc]init];
            _alertLabel.text = NSLocalizedString(@"开启全新之旅", @"开启全新之旅");
            _alertLabel.font = [UIFont systemFontOfSize:24];
            _alertLabel.textColor = [UIColor colorWithHexString:@"445560"];
            _alertLabel.textAlignment = NSTextAlignmentCenter;
            [imageView addSubview:_alertLabel];
            
        }
    }
    
    _transparentView = [[UIView alloc] init];
    [_transparentView setAlpha:0.0];
    [_introScrollView addSubview:_transparentView];
}

- (void)onHitBtnSkip:(UIButton *)btn
{
    [self shouldDismiss:NO];
}

- (void)refreshBootImage
{

#ifndef EMBED_DEMO

#if defined(ENABLE_AD_MODULE) || defined(Tap_Ad_Play_Guangdong)
    if (!_isFirstLaunch) {
        _adViewController = [[TSPlayAdViewController alloc] initWithAdBizTypeId:TSAdBizTypeIdGeneral adHostOpptId:TSAdHostOpptIdPhoneAppLaunch channelId:nil absTime:nil columnId:nil itemId:nil];
        
        [self addChildViewController:_adViewController];
        [self.view addSubview:_adViewController.view];
        [_adViewController.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width*1.5f)];
        [_adViewController didMoveToParentViewController:self];
        [_adViewController setDelegate:(id<TSPlayAdViewControllerDelegate>)self];
        [self setupAdCountDownLabel];
    }
    
#else

#ifdef SWITCH_LOCAITON_BRIGHT415
    
#else
    [[TSBootAdUtil sharedSingleton] getBootAdInfoListWithCompleted:^(NSArray *array, NSError *error) {
        
        NSDate *now = [NSDate date];
        NSMutableArray *arrBootAd = [NSMutableArray array];
        for (TSBootAdInfo *bootAd in array) {
            NSDate *start = [TSTimeUtil fullDateForTimeString:bootAd.startDate];
            NSDate *end   = [TSTimeUtil fullDateForTimeString:bootAd.endDate];
            if ([[start laterDate:now] isEqualToDate:[end earlierDate:now]]) {
                [arrBootAd addObject:bootAd];
            }
        }

        if (NO == TS_IS_ARRAY_NIL(arrBootAd)) {
            NSInteger randomNumber = arc4random()%([arrBootAd count]);
            bootAdInfo = [arrBootAd objectAtIndex:randomNumber];
            
            [self setupAdImgView];
            
            [adImgView sd_setImageWithURL:[NSURL URLWithString:bootAdInfo.imageUrl]];
            [adImgView setUserInteractionEnabled:YES];
        }
    }];

#endif
    
#endif
    
#endif
}

- (void)setupAdImgView
{
    if (nil == adImgView) {
        adImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width*1.5f)];
        [adImgView setBackgroundColor:[UIColor clearColor]];
        [adImgView setUserInteractionEnabled:YES];
        [self.loadingImageView setUserInteractionEnabled:YES];
        [self.loadingImageView addSubview:adImgView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapAd:)];
        [adImgView addGestureRecognizer:tapGesture];
        
        [self setupAdCountDownLabel];
    }
}

- (void)setupAdCountDownLabel
{
    if (nil == adCountDownLabel) {
        adCountDownLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.loadingImageView .frame.size.width-100, 40, 100, 20)];
        [adCountDownLabel setTextColor:[UIColor generalSelectedTintColor]];
        [adCountDownLabel setFont:[UIFont generalLargeFont]];
        [adCountDownLabel setTextAlignment:NSTextAlignmentCenter];
        [self.loadingImageView  addSubview:adCountDownLabel];
    }
}

- (void)onTapAd:(UIGestureRecognizer *)gesture
{
#ifdef SWITCH_LOCATION_FUZHOU
    NSString *strAdSafariUrl = bootAdInfo.targetUrl;
    [TSPreferenceUtil setGlobalKey:@"bootAdTargetUrl" value:strAdSafariUrl];
    [self onHitBtnSkip:nil];
#else

    NSString *strAdSafariUrl = bootAdInfo.targetUrl;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strAdSafariUrl]];
#endif
}

- (void)onHitRudderButton
{
    [_introScrollView setHidden:YES animated:YES];
    [self dismiss:YES];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    [_introScrollView setFrame:self.view.bounds];
    
    for (UIImageView *imageView in _arrGuideImageView) {
        NSInteger index = [_arrGuideImageView indexOfObject:imageView];
        [imageView setFrame:CGRectMake(0 + index*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _currentMaxX = CGRectGetMaxX(imageView.frame);
        
        if (index == _arrGuideImageView.count - 1) {
            [_rudderButton setFrame:CGRectMake(0, 0, self.view.bounds.size.width/6, self.view.bounds.size.width/6)];
            [_rudderButton setCenter:CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height *(4.0/5.0))];
            
            [_alertLabel setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 25)];
            [_alertLabel setCenter:CGPointMake(self.view.frame.size.width/2, _rudderButton.center.y+65)];
        }
    }
    [_transparentView setFrame:CGRectMake(_currentMaxX, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _currentMaxX = CGRectGetMaxX(_transparentView.frame);
    [_introScrollView setContentSize:CGSizeMake(_currentMaxX, self.view.frame.size.height)];
    
    
    
#ifdef EMBED_DEMO
#ifdef SWITCH_LOCATION_TRCBANK

    if (_animated == NO) {
        _animated = YES;
        
        CGFloat marginV = 320;
        CGFloat marginH = 180;
        
        [_homeUpImageView setFrame:CGRectMake(0, - (height - marginV), width, height)];
        [_homeLeftImageView setFrame:CGRectMake(- (width - marginH), 0, width, height)];
        [_homeRightImageView setFrame:CGRectMake(width - marginH, 0, width, height)];
        [_homeDownImageView setFrame:CGRectMake(0, height - marginV, - width, height)];
        
        NSTimeInterval duration = 0.8;
        
        [_homeUpImageView setFrame:CGRectMake(0, 0, width, height) animeted:YES option:UIViewAnimationOptionCurveEaseOut duration:duration];
        [_homeLeftImageView setFrame:CGRectMake(0, 0, width, height) animeted:YES option:UIViewAnimationOptionCurveEaseOut duration:duration];
        [_homeRightImageView setFrame:CGRectMake(0, 0, width, height) animeted:YES option:UIViewAnimationOptionCurveEaseOut duration:duration];
        [_homeDownImageView setFrame:CGRectMake(0, 0, width, height) animeted:YES option:UIViewAnimationOptionCurveEaseOut duration:duration];
    }

#endif
#endif
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.loadingImageView setHidden:NO];
    
    _prevStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle];
    
#ifdef EMBED_DEMO
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
#endif
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
#ifdef EMBED_DEMO
    [UIApplication sharedApplication].statusBarStyle = _prevStatusBarStyle;
#endif
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
#ifndef ENABLE_PORTALAPI_SEND_LOCATION_NAME
    __weak __typeof(self)weakSelf = self;
    [[TSSystemUtil sharedSingleton] getLocationChoseViewNeedShowWithCompleted:^(BOOL isNeeded, BOOL showUpdateInfo, NSArray *array, NSError *error) {
        
        if (isNeeded) {
            _arrLocations = array;
            [weakSelf showLocationSelectView];
        } else {
            
            if (showUpdateInfo == YES) {
                NSString *locationName = [TSPreferenceUtil getGlobalKey:PREF_USER_LOCATION_NAME];
                [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@:%@", NSLocalizedString(@"您已更新到地区", nil), locationName]];
            }
            
            if (_isFirstLaunch) {
                [self showIntroView];
            } else {
                [self dismiss:NO];
            }
        }
    }];
#endif
}

- (void)dismiss:(BOOL)isFirst
{
    [pageControl setHidden:YES];
    [_introScrollView setHidden:YES];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
#if defined(ENABLE_AD_MODULE) || defined(Tap_Ad_Play_Guangdong)
        // 首次启动时，新手引导完后才显示广告
        if (isFirst) {
            _adViewController = [[TSPlayAdViewController alloc] initWithAdBizTypeId:TSAdBizTypeIdGeneral adHostOpptId:TSAdHostOpptIdPhoneAppLaunch channelId:nil absTime:nil columnId:nil itemId:nil];
            
            [self addChildViewController:_adViewController];
            [self.view addSubview:_adViewController.view];
            [_adViewController.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width*1.5f)];
            [_adViewController didMoveToParentViewController:self];
            [_adViewController setDelegate:(id<TSPlayAdViewControllerDelegate>)self];
            [self setupAdCountDownLabel];
        } else {
            if (_adViewController.adData != nil) {
                if (_adViewController.adData.closeDuration.integerValue != -1) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_adViewController.adData.closeDuration.integerValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.skipBtn setHidden:NO];
                    });
                }
            } else {
                [self onHitBtnSkip:self.skipBtn];
            }
        }
#else
        if (bootAdInfo && bootAdInfo.duration > 0) {
            bootAdCountDown = bootAdInfo.duration;
            [self setupCountDownTimer:isFirst];
            
            [self.skipBtn setHidden:NO];
        } else {

            [self shouldDismiss:isFirst];
            [self.skipBtn setHidden:YES];
        }
#endif
    });
}

- (void)setupCountDownTimer:(BOOL)isFirst
{
    [NSTimer scheduledTimerWithTimeInterval:1.f block:^(NSTimer *timer) {
        if (bootAdCountDown > 0) {
            [adCountDownLabel setText:[NSString stringWithFormat:@"倒计时%lds", (long)bootAdCountDown]];
            bootAdCountDown --;
            [self setupCountDownTimer:isFirst];
            
        } else {
            [adCountDownLabel setText:@""];
            [self shouldDismiss:isFirst];
        }
    } repeats:NO];
}

#pragma mark - Private Methods

- (void)showLocationSelectView
{
    NSMutableArray *arrayLocationNames = [NSMutableArray arrayWithCapacity:0];
    NSInteger initialSelect = 0;
    for (TSLocation *location in _arrLocations) {
        if ([location.code isEqualToString:[TSPreferenceUtil getGlobalKey:PREF_USER_LOCATION_CODE]]) {
            initialSelect = [_arrLocations indexOfObject:location];
        }
        [arrayLocationNames addObject:location.name];
    }
    
    [TSSelectViewController showInViewController:self title:NSLocalizedString(@"请选择地区", nil) dataList:arrayLocationNames initialSelect:initialSelect cancelEnable:NO dismissed:^(BOOL confirm, NSInteger selectedIndex) {
        if (confirm == NO) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"请先选择地区", nil)];
        } else {
            TSLocation *location = [_arrLocations objectAtIndex:selectedIndex];
            [TSPreferenceUtil setGlobalKey:PREF_USER_LOCATION_NAME value:location.name];
            [TSPreferenceUtil setGlobalKey:PREF_USER_LOCATION_CODE value:location.code];
            
            if (_isFirstLaunch) {
                [self showIntroView];
            } else {
                [self dismiss:NO];
            }
        }
    }];
}

- (void)showIntroView
{
    [_introScrollView setHidden:NO];
#if defined(ENABLE_AD_MODULE) || defined(Tap_Ad_Play_Guangdong)
    [_adViewController adWillEnd];
#endif
    [pageControl setHidden:NO];
}

#pragma - mark - login

- (void)loginIntoApp
{
    [[TSSystemUtil sharedSingleton]getConfigUseCacheWithWhat:GetConfigeWhat_needLoginSwitch completed:^(NSDictionary *dicConfig, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *isNeedLogin = dicConfig[GetConfigeWhat_needLoginSwitch];
    
            if (TS_IS_STR_NOT_NIL(isNeedLogin)) {
                [TSPreferenceUtil setGlobalKey:@"isNeedLogin" value:isNeedLogin];
            }
            
            if ([isNeedLogin isEqualToString:@"true"]) {
                if (YES == [TSPreferenceUtil getGlobalBoolKey:IS_NEED_AUTO_LOGIN]) {
                    NSString *strUsername = [TSPreferenceUtil getGlobalKey:USERNAME_AUTO_LOGIN];
                    NSString *strPassword = [TSPreferenceUtil getSecretGlobalKey:PASSWORD_AUTO_LOGIN];
                    if (nil != strUsername && nil != strPassword) {
                        
                        _isNeedShowLogin = NO;
                        
                        [[TSAccountUtil sharedSingleton] loginWithUser4FuZhou:strUsername password:strPassword drmInfo:@"" isAutoLogin:YES completed:^(BOOL success, NSString *AAAToken, NSString *DRMToken, NSError *error) {
                            
                            _isLoginComeBack = YES;
                            
                            if (success) {
                                _isLoginSuccess = YES;
                                _isNeedShowLogin = NO;
                            }else{
                                _isLoginSuccess = NO;
                                _isNeedShowLogin = YES;
                            }
                            
                            if (_isShouldDismiss) {
                                //说明登录接口还没回来之前，已经调用了一次shouldDismiss
                                if (_isLoginSuccess) {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        if (self.didDismiss) {
                                            self.didDismiss(NO);
                                            self.didDismiss = nil;
                                        }
                                    });
                                }else{
                                    [self showLogin];
                                }
                            }
                        }];
                    }
                }else{
                    _isNeedShowLogin = YES;
                }
            }else{
                if (YES == [TSPreferenceUtil getGlobalBoolKey:IS_NEED_AUTO_LOGIN]) {
                    NSString *strUsername = [TSPreferenceUtil getGlobalKey:USERNAME_AUTO_LOGIN];
                    NSString *strPassword = [TSPreferenceUtil getSecretGlobalKey:PASSWORD_AUTO_LOGIN];
                    if (nil != strUsername && nil != strPassword) {
                        [[TSAccountUtil sharedSingleton] loginWithUser4FuZhou:strUsername password:strPassword drmInfo:@"" isAutoLogin:YES completed:^(BOOL success, NSString *AAAToken, NSString *DRMToken, NSError *error) {
                            if (success) {
                            }else{
                            }
                        }];
                    }
                }
                _isNeedShowLogin = NO;
            }
        });
    }];
}

- (void)showLogin
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleLoginStatusChange:)
                                                 name:TSLoginStatusDidChangeNotification
                                               object:nil];

    TSLogin4FuZhouViewController *login = [[TSLogin4FuZhouViewController alloc]init];
    login.isHiddenBack = YES;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)handleLoginStatusChange:(NSNotification *)noti
{
    NSString *isLoggedIn = [[noti userInfo] objectForKey:@"isLoggedIn"];
    if (isLoggedIn.integerValue == NO) {
        // 登录失败
        _isLoginSuccess = NO;
    } else {
        // 登录成功
        _isLoginSuccess = YES;
        if (self.didDismiss) {
            self.didDismiss(NO);
            self.didDismiss = nil;
        }
     }
}
#pragma mark - Auto Login

- (void)autoLogin
{
#if defined (ShowLoginAndRegister4FuZhou) || defined (SWITCH_LOCATION_415MASTER_GUANGDONG) || defined(SWITCH_LOCATION_CHANGSHA)
#if GD_LoginRegiset
    NSString *type = [TSPreferenceUtil getGlobalKey:LoginTypeFromUAP4GuangZhou];
    NSString *strUsername = [TSPreferenceUtil getGlobalKey:USERNAME_AUTO_LOGIN];
    NSString *strPassword = [TSPreferenceUtil getSecretGlobalKey:PASSWORD_AUTO_LOGIN];
    [[TSAccountUtil sharedSingleton] getSerialNoFromUAP:^(NSString *serialNo, NSError *error) {
        if (TS_IS_STR_NOT_NIL(serialNo)) {
            [[TSAccountUtil sharedSingleton] loginFromUAP:type loginparam:strUsername password:strPassword serialno:serialNo complete:^(BOOL success, NSString *newToken, NSString *userName, NSError *error) {
                if (success) {
                } else {
                    // 登录失败，将本地存储的用户名密码token等置为空。避免出现未登录情况下使用失效的用户信息去鉴权导致未知错误无法播放的问题
                    [TSPreferenceUtil setGlobalKey:USERNAME_AUTO_LOGIN value:@""];
                    [TSPreferenceUtil setSecretGlobalKey:PASSWORD_AUTO_LOGIN value:nil];
                    [TSPreferenceUtil setGlobalKey:PREF_USER_CURRENT value:@""];
                    [TSPreferenceUtil setKey:PREF_USER_TOKEN value:nil];
                    [TSPreferenceUtil setKey:UserCode value:nil];
                    [TSPreferenceUtil setSecretGlobalKey:PREF_PWD_CURRENT value:nil];
                    [TSPreferenceUtil setGlobalKey:LoginTypeFromUAP4GuangZhou value:@""];
                }
            }];
        }else{
        }
    }];
#else
    if (YES == [TSPreferenceUtil getGlobalBoolKey:IS_NEED_AUTO_LOGIN]) {
        NSString *strUsername = [TSPreferenceUtil getGlobalKey:USERNAME_AUTO_LOGIN];
        NSString *strPassword = [TSPreferenceUtil getSecretGlobalKey:PASSWORD_AUTO_LOGIN];
        if (nil != strUsername && nil != strPassword) {
            [[TSAccountUtil sharedSingleton] loginWithUser4FuZhou:strUsername password:strPassword drmInfo:@"" isAutoLogin:YES completed:^(BOOL success, NSString *AAAToken, NSString *DRMToken, NSError *error) {
                
                if (success) {
                    
                } else {
                    
                }
            }];
        }
    }
#endif
#else
    if (YES == [TSPreferenceUtil getGlobalBoolKey:IS_NEED_AUTO_LOGIN]) {
        NSString *strUsername = [TSPreferenceUtil getGlobalKey:USERNAME_AUTO_LOGIN];
        NSString *strPassword = [TSPreferenceUtil getSecretGlobalKey:PASSWORD_AUTO_LOGIN];
        if (nil != strUsername && nil != strPassword) {
            [[TSAccountUtil sharedSingleton] loginWithUser:strUsername password:strPassword drmInfo:@"" isAutoLogin:YES completed:^(BOOL success, NSString *AAAToken, NSString *DRMToken, NSError *error) {
                if (success) {
                    //nothing
                } else {
                    //nothing
                }
            }];
        }
    }

    [TSXMPPMessageHandler sharedSingleton];
#endif
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger scrollIndex = scrollView.contentOffset.x/scrollView.frame.size.width;
    
    if (scrollIndex != _prevScrollIndex) {
        if (scrollIndex == _arrGuideImageView.count - 1) {
            [self rotate:_rudderButton];
        } else if (scrollIndex == _arrGuideImageView.count) {
            [self dismiss:YES];
        }
    }
    
    [pageControl setCurrentPage:scrollIndex];

}

- (void)rotate:(UIView *)view
{
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = @(M_PI * 2.0);
    rotationAnimation.duration = 1;
    rotationAnimation.autoreverses = NO;
    rotationAnimation.repeatCount = 1;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}


- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)shouldDismiss:(BOOL)isFirst
{
#ifdef Loginsuccess_IntoApp
    
    _isShouldDismiss = YES;
    
    if ([[TSPreferenceUtil getGlobalKey:@"isNeedLogin"] isEqualToString:@"true"]) {
        if (_isNeedShowLogin) {
            [self showLogin];
        }else{
            if (_isLoginComeBack && _isLoginSuccess) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.didDismiss) {
                        self.didDismiss(isFirst);
                        self.didDismiss = nil;
                    }
                });
            }
        }
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.didDismiss) {
                self.didDismiss(isFirst);
                self.didDismiss = nil;
            }
        });
    }
    
#else
#ifndef EMBED_DEMO
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.didDismiss) {
            self.didDismiss(isFirst);
            self.didDismiss = nil;
        }
    });
#endif
#endif
    
}

- (void)onHitLoadingImage:(UITapGestureRecognizer *)gr
{
    CGPoint touchPoint = [gr locationInView:gr.view];
    BOOL inTagetSpace = (touchPoint.y > 116/2 && touchPoint.y < 416/2);
    
#ifdef SWITCH_LOCATION_TRCBANK
    inTagetSpace = (touchPoint.y > 800.0/2280 * height && touchPoint.y < 1280.0/2280 * height) && (touchPoint.x > 600.0/1242 * width && touchPoint.x < 1000.0/1242 * height);
#endif
    if (inTagetSpace) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *tabBC = [storyboard instantiateViewControllerWithIdentifier:@"RootTabBC"];
        [self presentViewController:tabBC animated:YES completion:nil];
    }
    
}

-(BOOL)shouldAutorotate
{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark - TSGpsLocationUtilDelegate
- (void)didGotCityName:(NSString *)city
{
    NSLog(@"[GPS]didGotCityName %@", city);
    [TSGpsLocationUtil sharedSingleton].delegateGpsLocation = nil;
    
#ifdef ENABLE_PORTALAPI_SEND_LOCATION_NAME
    [self checkAndShowLocationSelection];
#endif
}

- (void)didGotGps:(NSDictionary *)gpsDict
{
    NSLog(@"didGotGps %@", gpsDict);
    
    NSString *platformString = [[UIDevice currentDevice] getCurrentDeviceModel];
    
    NSString *province = [gpsDict objectForKey:@"province"];
    NSString *city = [gpsDict objectForKey:@"city"];
    NSString *county = [gpsDict objectForKey:@"county"];
#ifdef ENABLE_STATISTICS
    [TSStatisticsUtil sendStatisticsWithModel:platformString province:province city:city county:county completed:nil];
#endif
}

- (void)failedGetLocation:(NSError *)error
{
    NSLog(@"failedGetLocation %@", error);
    [TSGpsLocationUtil sharedSingleton].delegateGpsLocation = nil;
    [self checkAndShowLocationSelection];
    
    NSString *platformString = [[UIDevice currentDevice] getCurrentDeviceModel];
#ifdef ENABLE_STATISTICS
    [TSStatisticsUtil sendStatisticsWithModel:platformString province:nil city:nil county:nil completed:nil];
#endif
}

- (void)checkAndShowLocationSelection
{
    [[TSSystemUtil sharedSingleton] getLocationChoseViewNeedShowWithCompleted:^(BOOL isNeeded, BOOL showUpdateInfo, NSArray *array, NSError *error) {
        
        if (isNeeded) {
            _arrLocations = array;
       
#ifdef ENABLE_PORTALAPI_SEND_LOCATION_NAME  // 如果发送locationName，Portal只会返回一个地区
            if (!TS_IS_ARRAY_NIL(_arrLocations)) {
                TSLocation *locationItem = [_arrLocations objectAtIndex:0];
                [TSPreferenceUtil setGlobalKey:PREF_USER_LOCATION_NAME value:locationItem.name];
                [TSPreferenceUtil setGlobalKey:PREF_USER_LOCATION_CODE value:locationItem.code];
            }
            
            if (_isFirstLaunch) {
                [self showIntroView];
            } else {
                [self dismiss:NO];
            }
#else
            [self showLocationSelectView];
#endif
        } else {
            
            if (showUpdateInfo == YES) {
                NSString *locationName = [TSPreferenceUtil getGlobalKey:PREF_USER_LOCATION_NAME];
                [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@:%@", NSLocalizedString(@"您已更新到地区", nil), locationName]];
            }
            
            if (_isFirstLaunch) {
                [self showIntroView];
            } else {
                [self dismiss:NO];
            }
        }
    }];
}

#pragma mark -  <TSPlayAdViewControllerDelegate>
#if defined(ENABLE_AD_MODULE) || defined(Tap_Ad_Play_Guangdong)

- (void)adPlayDidReachEnd:(UIViewController *)adVC
{
    [self shouldDismiss:NO];
}

- (void)didClickAdWithGoToUrl:(NSString *)gotoUrl
{
    if ([gotoUrl hasPrefix:@"http://"] || [gotoUrl hasPrefix:@"https://"]) {
        // 说明是链接
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:gotoUrl]];
    } else if ([gotoUrl hasPrefix:@"UVideoUAS://"]) {
        // 说明是直播或点播。1.获取url中的type值，type 1直播 2点播；2.根据节目类型获取url中的channelid或programid
        NSString *strParams = [gotoUrl stringByReplacingOccurrencesOfString:@"UVideoUAS://" withString:@""];
        NSString *type = [self fetchUrlParam:@"type" url:strParams];
        NSString *adProgramId = @"";
        if (type.integerValue == 1) {
            adProgramId = [self fetchUrlParam:@"channelid" url:strParams];
        } else if (type.integerValue == 2) {
            adProgramId = [self fetchUrlParam:@"programid" url:strParams];
        }
        
        [TSPreferenceUtil setKey:@"adType" value:type];
        [TSPreferenceUtil setKey:@"adProgramId" value:adProgramId];
        [TSPreferenceUtil setBoolKey:@"TapAdToPlay" value:YES];
        [self shouldDismiss:NO];
    }
}

-(NSString *)fetchUrlParam:(NSString *)param url:(NSString *)url {
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",param];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        return [url substringWithRange:[match rangeAtIndex:2]];
    }
    return @"";
}

#endif


- (void)dealloc
{
    NSLog(@"TSSplashViewController dealloc");
}

@end
